package com.CST.service.impl.ys;

import com.CST.common.BaseEntity;
import com.CST.dto.ys.YsManageSubjectDTO;
import com.CST.entity.ys.YsDepartment;
import com.CST.entity.ys.YsManageSubject;
import com.CST.mapper.cst.ys.YsManageSubjectMapper;
import com.CST.service.ys.YsManageSubjectService;
import com.CST.service.ys.YsSubjectService;
import com.CST.util.ExcelTransfer;
import com.CST.vo.ys.YsManageSubjectListVO;
import com.CST.vo.ys.YsManageSubjectVO;
import com.CST.vo.ys.YsSubjectListVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author qtx
 * @since 2023-04-24
 */
@Service
public class YsManageSubjectServiceImpl extends ServiceImpl<YsManageSubjectMapper, YsManageSubject> implements YsManageSubjectService {

    private final YsSubjectService ysSubjectService;

    private final ExcelTransfer<YsManageSubjectVO> excelTransfer;

    public YsManageSubjectServiceImpl(@Lazy YsSubjectService ysSubjectService, ExcelTransfer<YsManageSubjectVO> excelTransfer) {
        this.ysSubjectService = ysSubjectService;
        this.excelTransfer = excelTransfer;
    }

    @Override
    public IPage<YsManageSubjectVO> listYsManageSubjectPage(YsManageSubjectDTO dto) {
        IPage<YsManageSubjectVO> iPage = baseMapper.selectPageNew(dto.getPage(), dto);
        iPage.getRecords()
                .forEach(this::setDepartment);
        return iPage;
    }

    @Override
    public void exportExcelYsManageSubject(HttpServletResponse response, YsManageSubjectDTO dto) {
        excelTransfer.exportExcel(response, baseMapper.selectNew(dto)
                        .stream()
                        .peek(this::setDepartment)
                        .collect(Collectors.toList()), "职能职能科目对照", "sheet",
                YsManageSubjectVO.class);
    }

    @Override
    public void exportExcelYsManageSubjectDemo(HttpServletResponse response) {
        excelTransfer.exportExcel(response, new ArrayList<>(), "职能职能科目对照", "sheet",
                YsManageSubjectVO.class);
    }

    @Override
    public void importExcelYsManageSubject(MultipartFile file) {
        List<YsSubjectListVO> vos = ysSubjectService.listYsSubject();
        Map<String, Integer> map = vos.stream()
                .collect(Collectors.toMap(e -> e.getSubjectCode() + e.getSubjectName(), YsSubjectListVO::getId));
        excelTransfer.importExcel(file, YsManageSubjectVO.class, list -> {
            list.forEach(e -> {
                YsManageSubject ysManageSubject = new YsManageSubject();
                BeanUtils.copyProperties(e, ysManageSubject);
                Integer integer = map.get(e.getSubjectCode() + e.getSubjectName());
                ysManageSubject.setSubjectId(integer.longValue());
                ysManageSubject.setFlag(Boolean.TRUE);
                save(ysManageSubject);
            });
            return new ArrayList<>();
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean inherit(Integer source, Integer target) {
        List<YsManageSubject> list = list(Wrappers.lambdaQuery(YsManageSubject.class)
                .eq(BaseEntity::getDeleteFlag, Boolean.FALSE)
                .eq(YsManageSubject::getYear, source));
        if (list.isEmpty()) {
            throw new RuntimeException("源头年份数据为空。");
        }
        list.forEach(e -> {
            e.setYear(target);
            e.setId(null);
            save(e);
        });
        return true;
    }

    @Override
    public List<YsManageSubjectListVO> listYsManageSubject(Long subjectId, String name) {
        return baseMapper.selectNew1(subjectId, name);
    }

    @Override
    public Integer selectByIds(YsManageSubject entity) {
        return baseMapper.selectByIds(entity);
    }

    private void setDepartment(YsManageSubjectVO vo) {
        StringBuilder names = new StringBuilder();
        StringBuilder codes = new StringBuilder();
        List<YsDepartment> departments =
                Optional.ofNullable(vo.getDepartments())
                        .orElse(new ArrayList<>());
        if (departments.isEmpty()) {
            return;
        }
        for (int i = 0; ; i++) {
            YsDepartment ysDepartment = departments.get(i);
            codes.append(ysDepartment.getDepartmentCode());
            names.append(ysDepartment.getDepartmentName());
            if (i == departments.size() - 1) {
                break;
            }
            names.append(", ");
            codes.append(", ");
        }
        vo.setDepartmentName(names.toString());
        vo.setDepartmentCode(codes.toString());
    }
}
